<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>购物车</title>
    <style>
        table 
        {
            border-collapse: collapse;
        }

        td
        {
            border: 1px solid #000;
            padding: 8px 16px;
        }
    </style>
</head>
<body>

    <table>
        <thead>
            <tr>
                <td>编号</td>
                <td>书籍名称</td>
                <td>出版日期</td>
                <td>价格</td>
                <td>购买数量</td>
                <td>操作</td>
            </tr>
        </thead>
        <tbody>

        </tbody>
    </table>

    <h1>总价格:<span class="totalPrice">￥0</span></h1>

    <script>

        //bookLists
        bookLists = 
        [
            {
              id:1,
              name:"《算法导论》",
              date:"2006-09",
              price:85,
              count:3  
            },
            {
              id:2,
              name:"《UNIX编程艺术》",
              date:"2006-02",
              price:59,
              count:2  
            },
            {
              id:1,
              name:"《编程珠玑》",
              date:"2008-10",
              price:39,
              count:5
            },
            {
              id:1,
              name:"《代码大全》",
              date:"2006-03",
              price:128,
              count:8  
            },
        ]

      //创建td节点并插入到tbody中
      var tbodyEl = document.querySelector("tbody");
      console.log(tbodyEl);
      for(var i = 0;i<bookLists.length;i++)
      {
         //创建tr元素
         var trEl = document.createElement("tr");
        for(key in bookLists[i])
        {
            //创建td元素
            var tdEl = document.createElement("td");
            console.log(bookLists[i][key])
            tdEl.textContent = bookLists[i][key];
            trEl.append(tdEl);
        }
        //在每一行添加删除按钮
        var btnEl = document.createElement("button");
        btnEl.textContent = "删除";
        var tdEl = document.createElement("td");
        tdEl.append(btnEl);
        trEl.append(tdEl);
        tbodyEl.append(trEl);

       //给button添加删除事件
       btnEl.onclick = function()
       {
          //找到tr
          var trEl = this.parentElement.parentElement;
          var deleteIndex = trEl.sectionRowIndex;
          trEl.remove();
          
          //也要删除数据表里面对印的数据并重新计算totalPrice
          bookLists.splice(deleteIndex,1);
          calcPrice();
       }

      }


      //计算总价格，使用reduce
    function calcPrice()
    {
      var totalEl = document.querySelector(".totalPrice");
      var totalPrice = bookLists.reduce(function(preSum,currentObject)
      {
           return preSum+currentObject.price*currentObject.count;
      },0) 

      totalEl.textContent = `￥${totalPrice}`;
    }

    calcPrice();

    </script>
    
</body>
</html>